<script setup>
import { onMounted, ref } from 'vue'
import { updateByIdApi, getAllApi } from '@/api/outbound/outboundorderpackage'
import { saveWeightApi } from '@/api/outbound/outboundorderweights'
import { ElMessage } from 'element-plus'
import Display from './display.vue'

const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const form = ref({
  invoiceCode: '',
  customerId: '',
  skuId: ''
})

// 状态映射
const statusMap = {
  1: '预发货',
  2: '确认发货',
  3: '拣货中',
  4: '拣货完成',
  5: '待打包',
  6: '待称重',
  7: '待发货',
  8: '已发货',
  9: '已签收'
}

// 获取数据
const getAll = async () => {
  const res = await getAllApi(
    form.value.invoiceCode,
    form.value.customerId,
    form.value.skuId,
    currentPage.value,
    pageSize.value
  )
  total.value = res.total
  tableData.value = res.rows
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getAll()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getAll()
}

const search = () => {
  currentPage.value = 1
  getAll()
}

// 打包弹窗
const visible = ref(false)
const selectedRow = ref(null)

const handleAdd = () => {
  // 选择一条记录进行打包
  if (!selectedRow.value) {
    ElMessage.warning('请先选择一条记录')
    return
  }
  visible.value = true
}
const ids = ref()
const handleSelectionChange = (val) => {
  ids.value = val.map(item => item.id)
  selectedRow.value = val[0] || null
}

const handleEdit = (row) => {
  // 查看详情
}

const delById = (id) => {
  // 删除
}

// 提交打包（实际是提交称重）
const submitPack = async (quantity) => {
  if (!selectedRow.value) return
  const { id } = selectedRow.value
  try {
    const updateRes = await updateByIdApi(id)
    // 构造称重数据
    const weightsData = {
      weights_code: generateWeightsCode(), // 生成称重单号
      outbound_order_detail_id: selectedRow.value.id,
      weights_emp_id: 1, // 假设当前登录员工ID
      weights_time: new Date().toISOString(),
      weight_val: quantity, // 数量作为重量值（可后续调整）
      weights_unit: 1, // 单位：克（或根据业务设定）
      saas_id: window.saasId || '',
      create_by: 'admin', // 当前用户账号
      create_time: new Date().toISOString()
    }

    // 调用称重接口
    const res = await saveWeightApi(weightsData)

    if (res.code === 1) {
      ElMessage.success('称重成功')
    } else {
      ElMessage.error(res.msg || '称重失败')
    }

    getAll() // 刷新列表
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  } finally {
    visible.value = false
  }
}
const generateWeightsCode = () => {
  return `W${Date.now()}${Math.floor(Math.random() * 1000)}`
}

onMounted(() => {
  getAll()
})
</script>

<template>
  <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
    <el-button @click="handleAdd" type="primary">打包</el-button>
  </div>

  <el-form :model="form" :inline="true" style="margin-bottom: 20px;">
    <el-form-item label="发货单号">
      <el-input v-model="form.invoiceCode" placeholder="请输入发货单号" />
    </el-form-item>
    <el-form-item label="客户名称">
      <el-input v-model="form.customerId" placeholder="请输入客户姓名" />
    </el-form-item>
    <el-form-item label="商品名称">
      <el-input v-model="form.skuId" placeholder="请输入商品ID" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="invoiceCode" label="发货单号" />
    <el-table-column prop="code" label="商品编码" />
    <el-table-column prop="title" label="商品名称" />
    <el-table-column prop="description" label="商品描述" />
    <el-table-column prop="customerId" label="客户姓名" />
    <el-table-column prop="outCount" label="订单数量" />
    <el-table-column prop="pendingPackQuantity" label="待打包数量" />
    <el-table-column prop="packedQuantity" label="已打包数量" />
    <el-table-column prop="productVolume" label="体积" />
    <el-table-column prop="createBy" label="创建人" />
    <el-table-column prop="packageTime" label="打包时间" />
    <el-table-column fixed="right" label="操作" width="200">
      <template #default="{ row }">
        <el-button size="small" @click="handleEdit(row)">查看</el-button>
        <el-button size="small" type="danger" @click="delById(row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>

  <!-- 打包弹窗 -->
  <el-dialog v-model="visible" title="打包" width="600px">
    <Display :row="selectedRow" @submit="submitPack" @close="visible = false" />
  </el-dialog>
</template>